<template>
  <div class="gift-container">
    <el-drawer v-model="dialogFormVisible" size="30%" @close="close">
      <template #header>
        <h4>{{ title }}</h4>
      </template>
      <template #default>
        <div class="content">
          <el-form
            ref="formRef"
            label-width="100px"
            :model="form"
            :rules="rules"
          >
            <el-form-item label="礼物名称" prop="name">
              <el-input v-model.trim="form.name" placeholder="请填写礼物名称" />
            </el-form-item>
            <el-form-item label="所需积分" prop="fee">
              <el-input v-model.trim="form.fee" placeholder="请填写所需积分" />
            </el-form-item>
            <el-form-item label="奖励积分" prop="income">
              <el-input
                v-model.trim="form.income"
                placeholder="请填写奖励积分"
              />
            </el-form-item>
            <el-form-item label="礼物图片" prop="url">
              <div class="upload-container">
                <el-upload
                  action="#"
                  list-type="picture-card"
                  :http-request="customRequest"
                  :file-list="fileList"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :limit="1"
                  :on-exceed="handleExceed"
                >
                  <template #default>
                    <el-icon><Plus /></el-icon>
                  </template>
                </el-upload>
              </div>
            </el-form-item>
            <el-dialog v-model="dialogVisible">
              <img :src="dialogImageUrl" alt="预览" style="width: 100%" />
            </el-dialog>
          </el-form>
        </div>
      </template>
      <template #footer>
        <div class="pay-button-group">
          <el-button type="primary" @click="submitForm('formRef')">
            保存
          </el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<script>
  import { doAdd } from '@/api/gift'
  import { fileAdd, fileDel } from '@/api/common'
  import { Delete, Plus } from '@element-plus/icons-vue'
  export default defineComponent({
    name: 'GiftDrawer',
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')
      const state = reactive({
        fileList: [], //定义一个数组来存放路径
        dialogImageUrl: null, //预览的图片路径
        dialogVisible: false, //预览图片弹框的状态(默认关闭)
        formRef: null,
        form: {
          name: '',
          fee: '',
          income: '',
          url: '',
        },
        title: '',
        dialogFormVisible: false,
        rules: {
          name: [
            { required: true, trigger: 'change', message: '请填写礼物名称' },
          ],
          fee: [
            { required: true, trigger: 'change', message: '请填写所需积分' },
          ],
          income: [
            { required: true, trigger: 'change', message: '请填写奖励积分' },
          ],
          url: [{ required: true, message: '请上传图片', trigger: 'change' }],
        },
      })
      // 自定义上传请求
      const customRequest = async (options) => {
        const formData = new FormData()
        formData.append('file', options.file)

        try {
          const res = await fileAdd(formData)
          console.log('上传接口响应:', res)
          if (res.code === 200) {
            options.onSuccess({
              status: 'success',
              name: options.file.name,
              url: res.data,
            })
            state.form.url = res.data
          } else {
            $baseMessage(res.msg, 'error', 'vab-hey-message-error')
          }
        } catch (error) {
          $baseMessage(error, 'error', 'vab-hey-message-error')
        }
      }

      //点击图片，利用弹框显示出预览图
      const handlePreview = (file) => {
        state.dialogImageUrl = file.url
        state.dialogVisible = true
      }

      const handleRemove = async (file) => {
        try {
          if (file.url) {
            // 调用后端删除接口
            await fileDel({ url: file.url })
            state.form.url = ''
            state.fileList = []
            $baseMessage('删除成功', 'success', 'vab-hey-message-success')
          }
        } catch (error) {
          $baseMessage(error, 'error', 'vab-hey-message-error')
        }
      }
      const handleExceed = () => {
        $baseMessage('最多只能上传一张图片', 'error', 'vab-hey-message-error')
      }
      const showEdit = (row) => {
        state.title = row ? '编辑礼物' : '添加礼物'
        if (row) {
          state.form = { ...row }
          state.fileList = row.url ? [{ url: row.url }] : []
        }
        state.dialogFormVisible = true
      }

      const close = () => {
        state.form = { url: '' } // 保留url字段重置
        state.fileList = [] // 清空文件列表
        state.dialogFormVisible = false
      }
      const submitForm = (formName) => {
        state[formName].validate(async (valid) => {
          state.baseForm = {
            id: state.form.id,
            name: state.form.name,
            fee: state.form.fee,
            income: state.form.income,
            url: state.form.url,
          }
          if (valid) {
            const { msg } = await doAdd(state.baseForm)
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            emit('fetch-data')
            close()
          }
        })
      }
      return {
        ...toRefs(state),
        showEdit,
        close,
        submitForm,
        customRequest,
        handlePreview,
        handleRemove,
        handleExceed,
        Delete,
        Plus,
      }
    },
  })
</script>

<style lang="scss">
  .gift-container {
    .el-drawer__header {
      height: 50px;
      padding: 0px 20px;
      margin-bottom: 0px;
      color: #000000;
      background-color: rgb(245, 245, 245);
    }

    .el-drawer__footer {
      text-align: center;
    }

    .content {
      .el-form-item__label {
        display: flex;
        justify-content: center;
        align-items: center;
        height: auto; /* 或者你需要的高度 */
      }
      .el-form-item__content {
        line-height: 25px;
      }
    }

    .upload-container {
      position: relative;
    }

    .hide-upload :deep(.el-upload--picture-card) {
      display: none;
    }

    .file-item {
      position: relative;
      width: 100%;
      height: 100%;
    }

    .image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .actions {
      position: absolute;
      right: -10px;
      top: -10px;
      display: none;
    }

    .file-item:hover .actions {
      display: block;
    }

    .delete {
      cursor: pointer;
      background: #fff;
      border-radius: 50%;
      padding: 5px;
      box-shadow: 0 0 6px rgba(0, 0, 0, 0.12);
    }
  }
</style>
